﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using DomainModel;
using Services.Abstract;

namespace Web
{
    public partial class Subjects : BasePage
    {
        public ISubjectService SubjectService { get; set; }
        public ITimetableUnitService TimetableUnitService { get; set; }
        public IPermissionService PermissionService { get; set; }

        protected new void Page_Load(object sender, EventArgs e)
        {
            SelectMenuItem("NavSubjects");

            BindListViewSubjects();
        }

        private void BindListViewSubjects()
        {
            var subjects = SubjectService.GetAll().OrderBy(s => s.Name).ToList();

            var ds = new List<Object>();

            foreach (var subject in subjects)
            {
                ds.Add(new
                {
                    Id = subject.Id,
                    Name = subject.Name,
                    ShortName = subject.ShortName,
                });
            }

            SubjectsList.DataSource = ds;
            SubjectsList.DataBind();
        }

        private void ShowEditSubjectForm(long subjectId = 0, string subjectName = null, string subjectShortName = null, bool showDeleteBtn = false)
        {
            if (subjectId != 0)
            {
                if (ViewState["subjectId"] == null)
                {
                    ViewState.Add("subjectId", subjectId);
                }
                else
                {
                    ViewState["subjectId"] = subjectId;
                }
            }

            TbSubjectName.Text = subjectName ?? "";
            TbSubjectShortName.Text = subjectShortName ?? "";

            ButtonDeleteSubject.Visible = showDeleteBtn;

            EditSubjectForm.Visible = true;
        }

        private void HideEditSubjectForm()
        {
            if (ViewState["subjectId"] != null)
            {
                ViewState.Remove("subjectId");
            }

            EditSubjectForm.Visible = false;
        }

        protected void BtnAddSubject_OnClick(object sender, EventArgs e)
        {
            ShowEditSubjectForm();
        }

        protected void BtnCancel_OnClick(object sender, EventArgs e)
        {
            HideEditSubjectForm();
        }

        protected void BtnSaveSubject_OnClick(object sender, EventArgs e)
        {
            string name = TbSubjectName.Text;
            string shortName = TbSubjectShortName.Text;

            Subject subject;
            if (ViewState["subjectId"] == null)
            {
                subject = new Subject(name) { ShortName = shortName };
            }
            else
            {
                long subjectId;
                try
                {
                    subjectId = long.Parse(ViewState["subjectId"].ToString());
                }
                catch (Exception)
                {
                    ShowSysMsg("Возникла непредвиденная ошибка.");
                    return;
                }

                subject = SubjectService.GetById(subjectId);

                if (subject == null)
                {
                    ShowSysMsg("Ошибка базы данных. Невозможно найти предмет.");
                    return;
                }

                subject.Name = name;
                subject.ShortName = shortName;
            }

            try
            {
                SubjectService.SaveOrUpdate(subject);

                BindListViewSubjects();

                HideEditSubjectForm();
            }
            catch (Exception exception)
            {
                ShowFormError(EditSubjectFormError.ClientID, exception.Message);
            }
        }

        protected void SubjectsList_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var dataKey = SubjectsList.DataKeys[e.Item.DisplayIndex];
            if (dataKey == null)
            {
                ShowSysMsg("Возникла непредвиденная ошибка.");
                return;
            }

            string subjectIdStr = dataKey.Value.ToString();

            long subjectId;
            try
            {
                subjectId = long.Parse(subjectIdStr);
            }
            catch (Exception)
            {
                ShowSysMsg("Возникла непредвиденная ошибка.");
                return;
            }

            var teachersList = (ListView)e.Item.FindControl("TeachersList");

            var teachers = TimetableUnitService.GetTeachersBySubjectId(subjectId).OrderBy(t => t.UserProfile.Fio);

            var ds = new List<Object>();

            foreach (var teacher in teachers)
            {
                ds.Add(new
                        {
                            Id = teacher.Id,
                            Fio = teacher.UserProfile.Fio,
                            Login = teacher.Login,
                        });
            }

            teachersList.DataSource = ds;
            teachersList.DataBind();
        }

        protected void BtnChangeSubject_OnClick(object sender, EventArgs e)
        {
            try
            {
                var listView = ((LinkButton)sender).Parent as ListViewDataItem;

                var dataKey = SubjectsList.DataKeys[listView.DataItemIndex];

                string subjectIdStr = dataKey.Value.ToString();
                long subjectId = long.Parse(subjectIdStr);
                var subject = SubjectService.GetById(subjectId);

                ShowEditSubjectForm(subjectId, subject.Name, subject.ShortName, true);
            }
            catch (Exception ex)
            {
                ShowSysMsg("Возникла непредвиденная ошибка.");
            }
        }

        protected void ButtonDeleteSubject_OnClick(object sender, EventArgs e)
        {
            if (ViewState["subjectId"] == null)
            {
                return;
            }

            long subjectId;
            try
            {
                subjectId = long.Parse(ViewState["subjectId"].ToString());
            }
            catch (Exception)
            {
                ShowSysMsg("Возникла непредвиденная ошибка.");
                return;
            }

            var subject = SubjectService.GetById(subjectId);

            try
            {
                SubjectService.Delete(subject);

                HideEditSubjectForm();
                BindListViewSubjects();
            }
            catch (Exception ex)
            {
                ShowFormError(EditSubjectFormError.ClientID, ex.Message);
            }
        }
    }
}